package com.itheima.domain.impl;

import com.itheima.domain.Observer;
import com.itheima.domain.Subject;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: MyTopicSubscriber
 * @Description:
 * @author: Yrd
 * @date: 2021-11-02 16:49
 */
public class MyTopicSubscriber implements Observer {
    private String name;
    private Subject topic;

    public MyTopicSubscriber(String name) {
        this.name = name;
    }

    public MyTopicSubscriber(Subject topic) {
        this.topic = topic;
    }

    public MyTopicSubscriber(String name, Subject topic) {
        this.name = name;
        this.topic = topic;
    }

    @Override
    public void update() {
        String message = (String) topic.getUpdate(this);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println("线程名称："+Thread.currentThread().getName()+"  "+ sdf.format(new Date()));
        if (message == null){
            System.out.println(name+":: No New Message");
        }else {
            System.out.println(name+":: Consuming message:: "+message);
        }

    }

    @Override
    public void setSubject(Subject subject) {
        this.topic = subject;

    }

    public void registerObserver(){
        this.topic.register(this);
    }

    public void unregisterObserver(){
        this.topic.unregister(this);
    }
}
